/**
 * 
 */
package com.gametime.setup;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Random;

import com.gametime.util.DBUtils;
import com.gametime.util.LogUtil;

import java.sql.PreparedStatement;

/**
 * @author dave
 *
 */
public class WeightGenerator {

	/**
	 * @param args
	 */
	private static WeightGenerator instance =null;
	private WeightGenerator()
	{
		
	}
	
	public static WeightGenerator getInstance()
	{
		if(instance == null)
		{
			instance = new WeightGenerator();
		}
		return instance;
	}
	
	public int getWeight(int heightValue) throws Exception
	{
		int result=0;
		Connection conn =null;
		try{
			conn = DBUtils.getInstance().getConnection();
			int maxRow = getMaxRows(heightValue,conn );
			Random r = new Random();
			if(maxRow < 1)
			  maxRow = 1;
			int randRow = r.nextInt(maxRow) + 1;
			result=getValue(randRow, heightValue, conn);
		}catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}finally 
		{
			DBUtils.closeConnection(conn);
		}
		
		return result;
	}
	private int getValue(int position, int heightValue, Connection conn) 
	throws Exception
	{
		int result=0;
		final String sql=
				"select value "+
				" from gen_hgt_grp_hgts h, gen_hgt_grp_wghts w "+
				" where h.height_value = ? "+
				" and h.gen_ht_grp_id = w.gen_hgt_grp_id"+
				" and seq=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, heightValue);
		ps.setInt(2,position);
		ResultSet rs = ps.executeQuery();
		while(rs.next())
		{
			result = rs.getInt(1);
		}
		rs.close();
		ps.close();
		return result;
	}

	private int getMaxRows(int heightValue, Connection conn) 
	throws Exception
	{
		int result=0;
		final String sql=
				"select count(*) "+
				" from gen_hgt_grp_hgts h, gen_hgt_grp_wghts w "+
				" where h.height_value = ? "+
				" and h.gen_ht_grp_id = w.gen_hgt_grp_id";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, heightValue);
		ResultSet rs = ps.executeQuery();
		while(rs.next())
		{
			result = rs.getInt(1);
		}
		rs.close();
		ps.close();
		return result;
	}

	

}
